﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace XLB.ExtensionMethodCore
{
    /// <summary>
    /// xml转换相关
    /// </summary>
    public static class XmlSerializeHelper
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string XmlSerialize<T>(this T obj)
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = obj.GetType();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj);
                sw.Close();
                return sw.ToString();
            }
        }

        /// <summary>
        /// 返序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="strXML">xml</param>
        /// <returns></returns>
        public static T XmlDesSrializer<T>(this string strXML) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 读取xml文件中指定节点的值
        /// </summary>
        /// <param name="xmlpath">xml文件物料路径</param>
        /// <param name="node">节点名称</param>
        /// <returns></returns>
        public static string ReadXmlFile(string xmlpath, string node)
        {
            try
            {

                XmlDocument doc = new XmlDocument();
                doc.Load(xmlpath);
                XmlNode xn = doc.SelectSingleNode("//" + node);
                return xn.InnerText;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 向xml文件指定节点写入值
        /// </summary>
        /// <param name="xmlpath">xml文件物料路径</param>
        /// <param name="node">节点名称</param>
        /// <param name="value">节点名称对应的值</param>
        public static void WriteXmlContent(string xmlpath, string node, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlpath);
                XmlNode xn = doc.SelectSingleNode("//" + node);
                xn.InnerText = value;
                doc.Save(xmlpath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
